package com.redwood.report.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Supeng on 2018/8/15.
 */

public class Utils {
    /**
     * 判断网络是否连接
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != connectivity) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 验证手机号码
     *
     * @param number
     * @return
     */
    public static boolean isMobileNum(String number) {
        Pattern p = Pattern.compile("^((1[3578]))\\d{9}$");
        // "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        Matcher m = p.matcher(number);
        return m.matches();
    }
    /**
     * 判断sdcard是否存在
     *
     * @return true存在可读写 false不存在不可读写
     */
    public static boolean sdacrdExist() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }
    /**
     * 获取版本名字
     *
     * @param context
     * @return version name
     */
    public static int getClientVersionCode(Context context) {
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            int appVersionCode = info.versionCode; // 版本名

            return appVersionCode; // 版本号
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 获取版本名字
     *
     * @param context
     * @return version name
     */
    public static String getClientVersionName(Context context) {
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String appVersion = info.versionName; // 版本名
            return appVersion; // 版本号
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 路径
     *
     * @return String
     */
    public static String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }
    public static void bytesToImageFile(byte[] bytes) {
        try {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaa.jpeg");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes, 0, bytes.length);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取文件存放根路径
    public static File getAppDir(Context context) {
        String dirPath = "";
        //SD卡是否存在
        boolean isSdCardExists = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
        boolean isRootDirExists = Environment.getExternalStorageDirectory().exists();
        if (isSdCardExists && isRootDirExists) {
            dirPath = String.format("%s/%s/", Environment.getExternalStorageDirectory().getAbsolutePath(), "wxr/");
        } else {
            dirPath = String.format("%s/%s/", context.getApplicationContext().getFilesDir().getAbsolutePath(), "wxr/");
        }

        File appDir = new File(dirPath);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        return appDir;
    }

    //获取录音存放路径
    public static File getAppRecordDir(Context context) {
        File appDir = getAppDir(context);
        File recordDir = new File(appDir.getAbsolutePath(), "record/");
        if (!recordDir.exists()) {
            recordDir.mkdir();
        }
        return recordDir;
    }
    public static String timerParse(String timer){
        String notimer="";
        try {
            if(TextUtils.isEmpty(timer)){
                return "";
            }
            //2018-11-28T21:50:01.707
            String mtimer=timer.replace("T"," ");
            notimer=mtimer.substring(0,mtimer.indexOf("."));
        }catch (Exception ex){

        }

        return notimer;
    }
    public static String timerchixvParse(String timer){
        if(TextUtils.isEmpty(timer)){
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String temp=timerParse(timer);
        Date nowDateT= null;
        try {
            nowDateT = sdf.parse(temp);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(nowDateT==null){
            return "";
        }
        return getDatePoor(new Date(),nowDateT);
    }
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nh = 1000 * 60 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少小时
        long hour = diff/ nh;
        return  hour + "小时" ;
    }
    public static String timerweek(long sconds){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(sconds);
        return sdf.format(c.getTime());
    }
    public static String getStingToHour(int miaoshu){
        return miaoshu/3600+"小时";
    }
    public static String getStingToHour3(int miaoshu){
        return miaoshu/3600+"";
    }
    public static String getStingToHour2(long miaoshu){
        String hourStr="00";
        String fenzhongstr="00";
        long hour=miaoshu/3600;
        long fenzhongt=miaoshu%3600;
        long fenzhong=fenzhongt/60;
        if(hour<10){
            hourStr="0"+hour;
        }else{
            hourStr=hour+"";
        }
        if(fenzhong<10){
            fenzhongstr="0"+fenzhong;
        }else{
            fenzhongstr=fenzhong+"";
        }
        return hourStr+":"+fenzhongstr;
    }
    public static float intFloatTuBiao(int miaoshu){
        int hour=miaoshu/3600;
        int fenzhongt=miaoshu%3600;
        int fenzhong=fenzhongt/60;
        float hourf=fenzhong/60f;
        return  hour+hourf;
    }

    public static String timertoHour(String timer){
        String hour="";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
        try {
            Date datehour=sdf.parse(timer);
            hour=sdf2.format(datehour);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hour;
    }
    /**
     6      * 时间戳转换成日期格式字符串
     7      * @param seconds 精确到秒的字符串
     8      * @param formatStr
     9      * @return
     10      */
  public static String timeStamp2Date(String seconds,String format) {
               if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
                        return "";
                   }
                 if(format == null || format.isEmpty()){
                      format = "yyyy-MM-dd";
                   }
                 SimpleDateFormat sdf = new SimpleDateFormat(format);
                return sdf.format(new Date(Long.valueOf(seconds)));
           }

    public static String getYear(String seconds,String format) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "yyyy";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
    }
    public static String getmonth(String seconds,String format) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "MM";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
    }
    public static int getDaysOfMonth(long seconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(seconds);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 取得月第一天
     *
     * @return
     */
    public static String getFirstDateOfMonth(long sconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(sconds);
        c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
        return sdf.format(c.getTime());
    }

    /**
     * 取得月最后一天
     *
     * @return
     */
    public static String getLastDateOfMonth(long sconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(sconds);
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
        return sdf.format(c.getTime());
    }


    /**
     * 当前季度的开始时间
     *
     * @return
     */
    public static String getCurrentQuarterStartTime(long seconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(seconds);
        int currentMonth = c.get(Calendar.MONTH) + 1;
        String now = "";
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 4);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = sdf.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }
    /**
     * 当前季度的结束时间
     *
     * @return
     */
    public static String getCurrentQuarterEndTime(long seconds) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(seconds);
        int currentMonth = c.get(Calendar.MONTH) + 1;
        String now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3) {
                c.set(Calendar.MONTH, 2);
                c.set(Calendar.DATE, 31);
            } else if (currentMonth >= 4 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 5);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 7 && currentMonth <= 9) {
                c.set(Calendar.MONTH, 8);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 10 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 11);
                c.set(Calendar.DATE, 31);
            }
            now = sdf.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     *
     * 1 第一季度 2 第二季度 3 第三季度 4 第四季度
     *
     * @return
     */
    public static int getSeason(long seconds) {

        int season = 0;

        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(seconds);
        int month = c.get(Calendar.MONTH);
        switch (month) {
            case Calendar.JANUARY:
            case Calendar.FEBRUARY:
            case Calendar.MARCH:
                season = 1;
                break;
            case Calendar.APRIL:
            case Calendar.MAY:
            case Calendar.JUNE:
                season = 2;
                break;
            case Calendar.JULY:
            case Calendar.AUGUST:
            case Calendar.SEPTEMBER:
                season = 3;
                break;
            case Calendar.OCTOBER:
            case Calendar.NOVEMBER:
            case Calendar.DECEMBER:
                season = 4;
                break;
            default:
                break;
        }
        return season;
    }

    public static String stringchanliang(String changliang){
        return ((int)(Long.parseLong(changliang)/10000f)*100)/100f+"";
    }

}
